/**
 * ExtremeTablePageUtil.java
 * Product:BaseLayer
 * Version:1.0
 * Copyright 2009 by DNE
 * All Rights Reserved.
 */
package com.site.util.extremetable;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.extremecomponents.table.context.Context;
import org.extremecomponents.table.context.HttpServletRequestContext;
import org.extremecomponents.table.limit.Filter;
import org.extremecomponents.table.limit.FilterSet;
import org.extremecomponents.table.limit.Limit;
import org.extremecomponents.table.limit.LimitFactory;
import org.extremecomponents.table.limit.Sort;
import org.extremecomponents.table.limit.TableLimit;
import org.extremecomponents.table.limit.TableLimitFactory;

/**
 * 辅助ExtremeTable获取分页信息的Util类
 */
public class ExtremeTablePageUtil {
	private static String tableId = "ec";
	//默认是default
	//可选值有default,notifyToDefault,persist,notifyToPersist
	private static String state = "default";
	
	private static String stateAttr = null;
	

	/**
	 * @param request
	 * @param defaultPageSize
	 * @return
	 */
    static public Limit getLimit(HttpServletRequest request, int defaultPageSize) {
        Context context = new HttpServletRequestContext(request);
       
        LimitFactory limitFactory = new TableLimitFactory(context,tableId,state,stateAttr);
        TableLimit limit = new TableLimit(limitFactory);
        
        int currentPageSize = limit.getCurrentRowsDisplayed();
        
        if(currentPageSize == 0)
        {
        	currentPageSize = defaultPageSize;
        }
        
        limit.setRowAttributes(Integer.MAX_VALUE, currentPageSize);
        
        return limit;
    }

    /**
     * 将Limit中的排序信息转化为Map{columnName,升序/降序}
     */
	static public Map<String,String> getSort(Limit limit) {
        Map<String,String> sortMap = new HashMap<String,String>();
        if (limit != null) {
            Sort sort = limit.getSort();
            if (sort != null && sort.isSorted()) {
                sortMap.put(sort.getProperty(), sort.getSortOrder());
            }
        }
        return sortMap;
    }
	
	public static Map<String,String> getFilterMap(Limit limit){
		Map<String,String> filterMap = new HashMap<String,String>();
		FilterSet set=limit.getFilterSet();
		Filter[] filters = set.getFilters();
		for (int i = 0; i < filters.length; i++) {
			filterMap.put(filters[i].getAlias(), filters[i].getValue());
		}
		return filterMap;
	}
}
